<template>
  <p-spin :spinning="confirmLoading">
    <p-form-model
      :model="form"
      ref="ruleForm"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"      
    >
      <p-divider orientation="left">基础信息</p-divider>
      <p-row>
        <p-col :span="8">
          <p-form-model-item hidden="ture" label="任务单号" ref="taskBillno" prop="taskBillno">
            <p-input
              readonly
              v-model="form.taskBillno"
              class="poros-input poros-input-disabled"
              placeholder="请输入任务单号"
            ></p-input>
          </p-form-model-item>
        </p-col>
      </p-row>
      <p-row>
        <p-col :span="8">
          <p-form-model-item label="来源类型" ref="sourceType" prop="sourceType">
            <j-dict-select-tag
              :disabled="table1disabled"
              type="list"
              v-model="form.sourceType"
              dictCode="mes_quality_improve_task_source_type"
              placeholder="请选择来源类型"
            />
          </p-form-model-item>
        </p-col>
        <p-col :span="8">
          <p-form-model-item label="提出人" ref="introducer" prop="introducer">
            <p-input
              :value="userInfo"
              readonly
              class="poros-input poros-input-disabled"
              v-model="formView.introducer_name"
              :defaultValue="uid"
            />
          </p-form-model-item>
        </p-col>
        <p-col :span="8">
          <p-form-model-item label="创建时间" ref="createTime" prop="createTime">
            <j-date readonly="ture" :formatter="dateFormat" v-model="form.createTime" />
          </p-form-model-item>
        </p-col>
      </p-row>
      <p-row>
        <p-col :span="8">
          <p-form-model-item label="产品编号" ref="mcode" prop="mcode">
            <f-popup
              :disabled="table1disabled"
              contextPath="basic-business"
              :value="form.mcode"
              :trigger-change="true"
              org-fields="mcode,mname"
              dest-fields="mcode,mname"
              code="mes_cpinfo_select"
              :add="this.url.add"
              isMultiSelect="popup"
              @oNvisible="oNvisible"
              @callback="popupCallback1"
            />
          </p-form-model-item>
        </p-col>
        <p-col :span="8">
          <p-form-model-item label="产品名称" ref="mname" prop="mname">
            <p-input disabled v-model="form.mname" placeholder="请输入产品名称"></p-input>
          </p-form-model-item>
        </p-col>
        <p-col :span="8">
          <p-form-model-item label="二级工序" ref="process2" prop="process2">
            <f-popup
              :disabled="table1disabled"
              contextPath="mes-craft"
              :value="form.process2"
              :trigger-change="true"
              org-fields="workstation_code,workstation_name"
              dest-fields="process2code,process2"
              code="mes_workstation_select"
              :add="this.url.add"
              isMultiSelect="popup"
              @oNvisible="oNvisible"
              @callback="popupCallback2"
            />
          </p-form-model-item>
        </p-col>
      </p-row>
      <p-row>
        <p-col :span="8">
          <p-form-model-item label="要求报告回复时间" ref="nrpReplytime" prop="nrpReplytime">
            <j-date
              :readOnly="table1disabled"
              placeholder="请选择要求报告回复时间"
              v-model="form.nrpReplytime"
              style="width: 100%"
            />
          </p-form-model-item>
        </p-col>
        <p-col :span="8">
          <p-form-model-item label="责任部门" ref="dutyDepartment" prop="dutyDepartment">
            <j-select-depart
              v-if="this.table1disabled === false"
              :disabled="table1disabled"
              placeholder="请选择责任部门"       
              v-model="form.dutyDepartment"
              departInit="03900000" 
              level = 3       c    
              :departName="formView.dutyDepartment_name"
            />
            <p-input
              v-if="this.table1disabled === true"
              :disabled="table1disabled"
              v-model="formView.dutyDepartment_name"
            />
          </p-form-model-item>
        </p-col>
        <p-col :span="8">
          <p-form-model-item label="处理人" ref="handler" prop="handler">
            <j-select-user-by-dep
              v-if="this.table1disabled === false"
              placeholder="请选择处理人"
              :disabled="table1disabled"
              :multi="false"
              v-model="form.handler"
              :departSelect="form.dutyDepartment"
              :userName="formView.handler_name"
            />
            <p-input
              v-if="this.table1disabled === true"
              :disabled="table1disabled"
              v-model="formView.handler_name"
            />
          </p-form-model-item>
        </p-col>
      </p-row>
      <p-row>
        <p-col :span="8">
          <p-form-model-item label="检验单号" ref="inspectBillno" prop="inspectBillno">
            <p-input :disabled="table1disabled" v-model="form.inspectBillno" placeholder="请输入检验单号"></p-input>
          </p-form-model-item>
        </p-col>
      </p-row>
      <p-row>
        <p-col :span="24">
          <p-form-model-item
            style="margin-left:-17px"
            label="问题描述"
            :label-col="{span:2, offset: 1}"
            :wrapper-col="{span:21, offset: -2}"
            ref="questionExplain"
            prop="questionExplain"
          >
            <p-textarea
              autosize="true"
              :disabled="table1disabled"
              v-model="form.questionExplain"
              rows="4"
              placeholder="请输入问题描述"
            />
          </p-form-model-item>
        </p-col>
      </p-row>
      <p-row v-if="table1disabled === false">
        <p-col :span="8">
          <p-form-model-item label="改善报告附件" ref="creportUrl" prop="creportUrl">
            <j-upload :disabled="table1disabled" 
             :multiple="true"
            v-model="form.creportUrl"></j-upload>
          </p-form-model-item>
        </p-col>
      </p-row>
      <div class="table2" v-if=" this.step !== 'table1' && status !== 'create'">
        <p-divider orientation="left">改善措施</p-divider>
        <p-row>
          <p-col :span="24">
            <p-form-model-item
              style="margin-left:-17px"
              label="改善措施简述"
              :label-col="{span:2, offset: 1}"
              :wrapper-col="{span:21, offset: -2}"
              ref="cmeasureExplain"
              prop="cmeasureExplain"
            >
              <p-textarea
                :autosize="true"
                :disabled="table2disabled"
                v-model="form.cmeasureExplain"
                rows="4"
                placeholder="请输入改善措施简述"
              />
            </p-form-model-item>
          </p-col>
        </p-row>
        <p-row>
          <p-col :span="8">
            <p-form-model-item label="措施预计完成时间" ref="measureYeTime" prop="measureYeTime">
              <j-date
                :readOnly="table2disabled"
                placeholder="请选择措施预计完成时间"
                v-model="form.measureYeTime"
                style="width: 100%"
              />
            </p-form-model-item>
          </p-col>
          <p-col :span="8">
            <p-form-model-item label="处理人" ref="currentHandler" prop="currentHandler">
              <p-input :disabled="true" v-model="formView.currentHandler_name" />
            </p-form-model-item>
          </p-col>
          <p-col :span="8">
            <p-form-model-item label="处理时间" ref="handleTime" prop="handleTime">
              <j-date
                :readOnly="table2disabled"
                placeholder="请选择处理时间"
                v-model="form.handleTime"
                style="width: 100%"
              />
            </p-form-model-item>
          </p-col>
        </p-row>
        <p-row>
          <p-col :span="8">
            <p-form-model-item label="改善报告附件" ref="creportUrl" prop="creportUrl">
              <j-upload :disabled="table2disabled" 
              :multiple="true"
              v-model="form.creportUrl"></j-upload>
            </p-form-model-item>
          </p-col>
        </p-row>
      </div>
      <div class="table1" v-if="status === '2' || status === '1' && step === 'table7'">
        <p-divider orientation="left">流程处理</p-divider>
        <p-row>
          <p-col :span="8">
            <p-form-model-item label="是否可结案" ref="isCloseFile" prop="isCloseFile">
              <j-dict-select-tag
                type="radio"
                :disabled="table3disabled"
                v-model="form.isCloseFile"
                dictCode="mes_isCloseFile"
                placeholder="请选择是否可结案"
              />
            </p-form-model-item>
          </p-col>
          <p-col :span="8">
            <p-form-model-item label="附件" ref="annexUrl" prop="annexUrl">
              <j-upload :disabled="table3disabled" v-model="form.annexUrl"></j-upload>
            </p-form-model-item>
          </p-col>
        </p-row>
        <p-row>
          <p-col :span="24">
            <p-form-model-item
              label="措施完成情况说明"
              style="margin-left:-17px"
              :label-col="{span:3, offset: -1}"
              :wrapper-col="{span:21, offset: 0}"
              ref="mefConditionRemark"
              prop="mefConditionRemark"
            >
              <p-textarea
                :autosize="true"
                :disabled="table3disabled"
                v-model="form.mefConditionRemark"
                rows="4"
                placeholder="请输入措施完成情况说明"
              />
            </p-form-model-item>
          </p-col>
        </p-row>
        <p-row>
          <p-col :span="8">
            <p-form-model-item label="当前处理人" ref="remark" prop="remark">
              <p-input disabled v-model="formView.remark_name" />
            </p-form-model-item>
          </p-col>
          <p-col :span="8">
            <p-form-model-item label="验证时间" ref="checkTime" prop="checkTime">
              <j-date disabled placeholder="请选择验证时间" v-model="form.checkTime" style="width: 100%" />
            </p-form-model-item>
          </p-col>
        </p-row>
      </div>
      <p-col :span="8">
        <p-form-model-item
          hidden="ture"
          label="流程实例ID"
          ref="processInstanceId"
          prop="processInstanceId"
        >
          <p-input v-model="form.processInstanceId" placeholder="请输入流程实例ID"></p-input>
        </p-form-model-item>
      </p-col>
      <div v-if="status === 'create'" style="margin: 10px 0 0;text-align: center;">
        <p-button @click="submit" :loading="loadingSum" type="primary" style="margin-right:10px">提交</p-button>
        <p-button @click="close" :loading="loadingSum">关闭</p-button>
      </div>
    </p-form-model>
  </p-spin>
</template>

<script>
import { httpAction, putAction, getAction, api } from '@/api/manage'
import processApi from '@/api/process'
import { getUserByUid,getOrgByCodes } from '@/api/api'
import { getParameterByName } from '@/utils/util'
import { SubmitOnchangMixin } from '@/mixins/SubmitOnchangMixin'
import { validateDuplicateValue } from '@/utils/util'
import dayjs from 'dayjs'
import JDate from '@/components/jeecg/JDate'
import JUpload from '@/components/jeecg/JUpload'
import JSelectDepart from '@/components/jeecgbiz/JSelectDepartQm'
import JSelectUserByDep from '@/components/jeecgbiz/JSelectUserByDepQm'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import { moment, now } from 'moment'
import process from '@/api/process'
import Bus from '@/utils/bus'

export default {
  inject: ['routeClose','reload'],
  name: 'MesQcQualityImproveTask_1Modal',
  mixins: [SubmitOnchangMixin],

  components: {
    JDate,
    JUpload,
    JSelectDepart,
    JSelectUserByDep,
    JDictSelectTag,
    moment,
  },
  props: {
    step: {
      type: String,
      required: true,
    },
    status: {
      type: String,
      required: true,
    },
    processInstanceId: {
      type: String,
      required: true,
    },
    taskId: {
      type: String,
      required: true,
    },
  },
  data() {
    let checkbillno = (rule, value, callback) => {
      if (value === '' || typeof(value) == "undefined" || value == null) {
        return callback()
      } else {
        getAction(
          this.url.checkbillno +
            '?billno=' +
            value +
            '&type=' +
            this.form.sourceType
        ).then((res) => {
          const result = res.data
          if (result === true) {
            callback()
          } else {
            callback(new Error('单号不存在!'))
          }
        })
      }
    }
    return {
      processDefinitionName: '',
      loadingSum: false,
      table1disabled: false,
      table2disabled: false,
      table3disabled: false,
      form: {
        createTime: this.nowday(),
        taskBillno: '',
        sourceType: '',
        questionExplain: '',
        dutyDepartment: '',
        replyDate: '',
        replyOverdue: '',
        processingCycle: '',
        taskStatus: '',
        annexUrl: '',
        introducer: this.userInfo(),
        initparent: '',
        mcode: '',
        mname: '',
        process2: '',        
        nrpReplytime: '',
        handler: '',
        handleTime: '',
        inspectBillno: '',
        creportUrl: '',
        cmeasureExplain: '',
        measureYeTime: '',
        operation: '',
        currentHandler: '',
        reviewTime: '',
        isCloseFile: '0',
        mefConditionRemark: '',
        checkTime: '',
        processInstanceId: '',
        variables: {},  
        step:''      
      },
      formView:{},
      tableData: {},
      title: '操作',
      width: 1200,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      visible: false,
      model: {},
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      rules: {
        sourceType: [
          { required: true, message: '请输入来源类型!', trigger: 'blur' },
        ],
        questionExplain: [
          { required: true, message: '请输入问题描述!', trigger: 'blur' },
        ],
        dutyDepartment: [
          { required: true, message: '请输入责任部门!', trigger: 'blur' },
        ],
        replyDate: [],
        replyOverdue: [],
        processingCycle: [],
        annexUrl: [],
        introducer: [],
        mcode: [],
        mname: [],
        process2: [],
        nrpReplytime: [
          {
            required: true,         
            trigger: 'change',           
            validator: (rule, value, callback) => {
              if (value === '') {
                callback(new Error('请输入要求报告回复日期！'))
              } 
              else if (dayjs(value).diff(dayjs(),'day') < 0) {
                callback(new Error('要求报告回复日期不能小于创建日期！'))
              }               
              else {
                callback()
              }
            },
          },
        ],
        handler: [
          { required: true, message: '请输入处理人!', trigger: 'blur' },
        ],
        handleTime: [ { required: true, message: '请输入处理时间!', trigger: 'blur' },],
        inspectBillno: [{ validator: checkbillno, trigger: 'blur' }],
        creportUrl: [
          { required: true, message: '请上传附件!', trigger: 'blur' },
        ],
        cmeasureExplain: [
          { required: true, message: '请输入改善措施!', trigger: 'blur' },
        ],
        measureYeTime: [
          {
            required: true,
            message: '请输入措施预计完成时间!',
            trigger: 'blur',
          },
        ],
        operation: [],
        currentHandler: [
          { required: true, message: '请输入处理人!', trigger: 'blur' },
        ],
        reviewTime: [],
        isCloseFile: [
          { required: true, message: '请选择!', trigger: 'change' },
        ],
        mefConditionRemark: [{ required: true, message: '请输入措施完成情况说明!', trigger: 'blur' },],
        checkTime: [
          { required: true, message: '请输入验证时间!', trigger: 'blur' },
        ],
        processInstanceId: [],
        createTime: [],
      },
      url: {
        add: '/mes-quality/mesQcQualityImproveTask_1/submit',
        edit: '/mes-quality/mesQcQualityImproveTask_1/getByProcessId',
        checkbillno: '/mes-quality/mesQcQualityImproveTask_1/checkbillno',
        rejectTask: '/mes-quality/mesQcQualityImproveTask_1/back',
      },
    }
  },
  created() {
    // 获取当前人的uid
    process.userInfo().then((res) => {
      if (res.code === 0) {
        let curData = res.data
        //  console.log(curData)
        this.uid = curData.uid
        this.name = curData.name
        if (this.status !== 'create') {
          // 获取流程表单信息
          this.loading = true
          this.getFormData()
          if (this.form.handler === null || this.form.handler === '') {
            this.form.handler = this.userInfo()
            //this.formView.handler_name = this.userName()
          }
          if (
            (this.step == 'table7' && this.form.checkTime === null) ||
            this.form.checkTime === ''
          ) {
            this.form.checkTime = this.nowday()
          }
          if (this.step == 'table3' && this.form.reviewTime === null || this.form.reviewTime === '') {
            this.form.reviewTime = this.nowday()
          }
          if (
            (this.step == 'table7' && this.form.remark === null) ||
            this.form.remark === ''
          ) {
            this.form.remark = this.userInfo()
            this.$set(this.formView, 'remark_name', this.userName())
          }

          if (
            (this.step == 'table2' && this.form.handleTime === null) ||
            this.form.handleTime === ''
          ) {
            this.form.currentHandler = this.userInfo()
            this.$set(this.formView, 'currentHandler_name', this.userName())
            this.form.handleTime = this.nowday()
          }         
          this.loading = false
         // console.log('处理人：' + this.form.handler_name)
        } else {
          this.form.introducer = this.uid
          this.formView.introducer_name = this.name          
          this.$set(this.formView, 'introducer_name', this.name)
          this.form.createTime = this.nowday()
          this.form.initparent = curData.orgPosDtos[0].parentUid
          this.form.introducerDepartment = curData.orgPosDtos[0].orgCode
          console.log('parentUid：' + this.form.initparent)

        }
      }
    })

    if (this.status === 'create' || this.step === 'table1') {
      this.table1disabled = false
      this.table2disabled = true
      this.table3disabled = true
    } else if (this.step === 'table2') {
      this.table1disabled = true
      this.table2disabled = false
      this.table3disabled = true
    } else if (this.step === 'table7') {
      this.table1disabled = true
      this.table2disabled = true
      this.table3disabled = false
    } else {
      this.table1disabled = true
      this.table2disabled = true
      this.table3disabled = true
    }
    console.log('status：' + this.status)
    console.log('table1disabled：' + this.table1disabled)
    console.log('table2disabled：' + this.table2disabled)
  },
  computed: {},
  watch: {},
  mounted() {
    var _this = this
    Bus.$on('prevSubmit', (val) => {
      console.log('正在提交表单数据')
      _this.submitForm2(val) 
      console.log('可以提交了 表单一数据', val)
    })
   
    Bus.$on('Formvalidat', (val) => {
      _this.$refs.ruleForm.validate((valid) => {     
         Bus.$emit('nextValidat', valid) 
        })
   })
  },
  methods: {
    close() {
      this.routeClose(this.$route)  
      this.reload()   
    },
    nowday() {
      return dayjs().format('YYYY-MM-DD')
    },
    checkBill() {
      getAction(
        this.url.checkbillno +
          '?billno=' +
          value +
          '&type=' +
          this.form.sourceType
      ).then((res) => res.data)
      const result = res.data
      return result
    },
    userInfo() {
      const userinfo = this.$store.state.user.uid
      //console.log('userinfo：' + userinfo)
      return userinfo
    },
    userName() {
      const userName = this.$store.state.user.name
      return userName
    },
    async getuserInfo() {
      const res = await process.userInfo()
      if (res.code === 0) {
        let curData = res.data
        //  console.log(curData)
        this.uid = curData.uid
        this.name = curData.name
      }
    },
    async getFormData() {
      const res = await getAction(this.url.edit + '/' + this.processInstanceId)
      if (res.code === 0) {
        let curData = res.data
        this.form = curData
        this.getUser(this.form.handler, 'handler_name')
        this.getUser(this.form.introducer, 'introducer_name')
       
        this.getOrg(this.form.dutyDepartment, 'dutyDepartment_name')
        if (
          (this.step == 'table7' && this.form.checkTime === null) ||
          this.form.checkTime === ''
        ) {
          this.form.checkTime = this.nowday()
          this.$set(this.form, 'checkTime', this.nowday())
          this.form.remark = this.userInfo()   
          this.$set(this.formView, 'remark_name', this.userName())
        }else{
          this.getUser(this.form.remark, 'remark_name')
        }

        if (
          (this.step == 'table2' && this.form.handleTime === null) ||
          this.form.handleTime === ''
        ) {
          this.form.handleTime = this.nowday()
          this.form.currentHandler = this.userInfo()     
          this.$set(this.form, 'handleTime', this.nowday())
          this.$set(this.formView, 'currentHandler_name', this.userName())
        }else{
          this.getUser(this.form.currentHandler, 'currentHandler_name')
        }


        if (this.step == 'table3' && this.form.reviewTime === null || this.form.reviewTime === '') {
            this.form.reviewTime = this.nowday()
            this.$set(this.form, 'reviewTime', this.nowday())
          }

      }
    },
    getUser(uid, str) {
      getUserByUid(uid).then((res) => {
        if (res.code === 0) {
          var name = res.data.name
          this.$set(this.formView, str, name)
        }
      })
    },
    getOrg(oid, str) {
      getOrgByCodes({'codes':oid}).then((res) => {
        if (res.code === 0) {
          var name = res.data[0].name
          this.$set(this.formView, str, name)
        }
      })
    },
    getRuleCodeValue() {
      let param = {
        commonFormData: this.model,
        rules: [
          { ruleCode: 'mes_qualityImprove_code', columnName: 'taskBillno' },
        ],
      }

      putAction(api.ruleBaseURL, param).then((res) => {
        // 执行成功，获取返回的值，并赋到页面上
        if (res.success) {
          //  console.log('生成的编码：' + res.data)
          const item = res.data
          this.form.taskBillno = item.taskBillno
        }
      })
    },
    popupCallback1(row) {
      this.form.mcode = row.mcode
      this.form.mname = row.mname
    },
    popupCallback2(row) {
      this.form.process2 = row.process2 
     
    },   
    submitForm2(event) {
      let _that = this
      this.form.taskId = this.taskId
      this.form.step = this.step
      console.log('表单数据', this.form)
      for (const key in this.form) {
        // 去除对象内多余的空值key
        if (this.form[key] === '' || this.form[key] === null) {
          delete this.form[key]
        }
      }      
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          httpAction(this.url.add, this.form, 'post').then((res) => {
            if (res.code == '0') {
              //console.log('提交表单数据成功', res)
              // this.$message.success("提交成功")
              let variable = {}
              variable.inititor = this.form.introducer
              variable.initparent = this.form.initparent
              variable.handler = this.form.handler
              variable.dutyDepartment = this.form.dutyDepartment
              Bus.$emit('nextSubmit', variable)        
            } else {
              console.log('提交表单数据失败', res)
              this.$message.warning(res.msg)
            }
          })
        }
      })
    },
    submitFrom(url, params, method) {
      httpAction(url, params, method).then((res) => {
        console.log(res)
        if (res.code == '0') {
          this.$message.success('提交成功')
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    submit() {
      const that = this

      // 触发表单验证
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          for (const key in this.form) {
            // 去除对象内多余的空值key
            if (this.form[key] === '' || this.form[key] === null) {
              delete this.form[key]
            }
          }
          console.log('开始提交')
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          //新增或修改表单数据
          console.log(this.form)
          httpurl += this.url.add
          method = 'post'
          console.log('表单提交数据', this.form)
          if (this.status === 'create') {
            let param = {
              commonFormData: this.model,
              rules: [
                {
                  ruleCode: 'mes_qualityImprove_code',
                  columnName: 'taskBillno',
                },
              ],
            }

            putAction(api.ruleBaseURL, param).then((res) => {
                // 执行成功，获取返回的值，并赋到页面上
                if (res.success) {
                  //  console.log('生成的编码：' + res.data)
                  const item = res.data
                  this.form.taskBillno = item.taskBillno
                  return this.submitFrom(httpurl, this.form, method)                  
                }
              })
              .then((res2) => {
                   setTimeout(() =>{
                      return this.close() 
                    },1000);  
              })
          } else {
            this.submitFrom(httpurl, this.form, method).then((res) => {
                   if (res.success) {
                      console.log('提交成功')  
                   }                    
            })
          }
        }else{
          return false;
        }
      })
    },   
  },
}
</script>
